package com.hui.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.hui.config.security.constant.AuthError;
import com.hui.config.security.utils.CrosUtil;
import com.hui.dto.JsonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 1.没有登录的处理2.认证不通过后的处理
 * 用户访问资源时，发生授权异常（AuthenticationException）或认证异（AccessDeniedException），
 * ExceptionTranslationFilter通过调用AuthenticationEntryPoint的commence方法发起认证过程。
 */
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg(AuthError.NOT_LOGIN.msg);
        jsonResult.setCode(AuthError.NOT_LOGIN.code);
        CrosUtil.crosOrgin(request, response);
        response.getWriter().write(JSONObject.toJSONString(jsonResult));
    }
}
